package iblobs

import (
	"fmt"

	"gitee.com/djaf/my-certs/app/classes/blobs"
	"gitee.com/djaf/my-certs/app/data/database"
	"gitee.com/djaf/my-certs/app/data/dxo"
	"gitee.com/djaf/my-certs/app/data/entity"
	"github.com/starter-go/security/random"
	"gorm.io/gorm"
)

// BlobDaoImpl ...
type BlobDaoImpl struct {

	//starter:component

	_as func(blobs.DAO) //starter:as("#")

	Agent       dxo.DatabaseAgent  //starter:inject("#")
	UUIDService random.UUIDService //starter:inject("#")

}

func (inst *BlobDaoImpl) _impl() blobs.DAO {
	return inst
}

func (inst *BlobDaoImpl) model() *entity.BLOB {
	return new(entity.BLOB)
}

func (inst *BlobDaoImpl) listModel() []*entity.BLOB {
	return make([]*entity.BLOB, 0)
}

func (inst *BlobDaoImpl) makeResult(o *entity.BLOB, res *gorm.DB) (*entity.BLOB, error) {
	err := res.Error
	if err != nil {
		return nil, err
	}
	return o, nil
}

// Find ...
func (inst *BlobDaoImpl) Find(db *gorm.DB, id dxo.BlobID) (*entity.BLOB, error) {
	db = inst.Agent.DB(db)
	o1 := inst.model()
	res := db.First(o1, id)
	return inst.makeResult(o1, res)
}

// List ...
func (inst *BlobDaoImpl) List(db *gorm.DB, query *blobs.Query) ([]*entity.BLOB, error) {

	db = inst.Agent.DB(db)
	if query == nil {
		query = new(blobs.Query)
	}

	list := inst.listModel()
	item := inst.model()

	finder := new(database.Finder)
	finder.DB = db
	finder.ItemModel = item
	finder.ListModel = &list
	finder.Pagination = &query.Pagination
	finder.QueryString = ""
	finder.QueryArgs = []any{}

	err := finder.Find()
	if err != nil {
		return nil, err
	}
	return list, nil
}

// Insert ...
func (inst *BlobDaoImpl) Insert(db *gorm.DB, item *entity.BLOB) (*entity.BLOB, error) {

	uuid := inst.UUIDService.Build().Class("entity.Blob").Generate()

	item.ID = 0
	item.UUID = uuid

	db = inst.Agent.DB(db)
	res := db.Create(item)
	return inst.makeResult(item, res)
}

// Update ...
func (inst *BlobDaoImpl) Update(db *gorm.DB, id dxo.BlobID, fn func(item *entity.BLOB)) (*entity.BLOB, error) {
	return nil, fmt.Errorf("unsupported")
}

// Remove ...
func (inst *BlobDaoImpl) Remove(db *gorm.DB, id dxo.BlobID) error {
	item := inst.model()
	db = inst.Agent.DB(db)
	res := db.Delete(item, id)
	return res.Error
}
